//
//  ViewController.m
//  KVO
//
//  Created by eport on 2021/1/9.
//

#import "ViewController.h"
#import "Person.h"
#import "NSObject+KVO.h"

@interface ViewController ()
@property(nonatomic,strong)Person *p;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.p = [[Person alloc]init];
    self.p.name = @"小新";
    self.p.age = 15;
    
//    [self.p addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    
    
    
//    [self.message PG_addObserver:self forKey:NSStringFromSelector(@selector(text))
//                       withBlock:^(id observedObject, NSString *observedKey, id oldValue, id newValue) {
//                           NSLog(@"%@.%@ is now: %@", observedObject, observedKey, newValue);
//                           dispatch_async(dispatch_get_main_queue(), ^{
//                               self.textfield.text = newValue;
//                           });
//
//    }];
//
    
    [self.p wx_addObserver:self keyPath:@"name" withBlock:^(id OberverObject, NSString *observerKey, id oldValue, id newValue) {
        
        NSLog(@"OberverObject----%@",OberverObject);
        NSLog(@"observerKey----%@",observerKey);
        NSLog(@"oldValue----%@",oldValue);
        NSLog(@"newValue----%@",newValue);
        
    }];
    
  
}


#pragma mark - kvo的回调方法(系统提供的回调方法)
//keyPath:属性名称
//object:被观察的对象
//change:变化前后的值都存储在change字典中
//context:注册观察者的时候,context传递过来的值
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    id oldName = [change objectForKey:NSKeyValueChangeOldKey];
    NSLog(@"oldName----------%@",oldName);
    id newName = [change objectForKey:NSKeyValueChangeNewKey];
    NSLog(@"newName-----------%@",newName);
    //当界面要消失的时候,移除kvo
//    [object removeObserver:self forKeyPath:@"name"];
}

-(void)dealloc{
    [self removeObserver:self forKeyPath:@"name"];
    [self wx_removeObserver:self forKeyPath:@"name"];
    
}


- (IBAction)buttonAction:(id)sender {
    
    self.p.name = @"小明";
}


@end
